// A-S-M team
// Project: BattleCity

#include "movingobject.h"
#include "play.h"

MovingObject::MovingObject(CL_String sprite_name, float x, float y, ObjectType type, float maxspeed) : GObject(sprite_name, x, y, type)
{
	_maxspeed = maxspeed;
	stopMove();
	setDirection(UP);
	Play::getInstance()->registerAtField(this);
}

void MovingObject::startMove()
{
	_moving=true;
}

void MovingObject::startMove(Direction direction)
{
	setDirection(direction);
	startMove();
}

void MovingObject::stopMove()
{
	_moving=false;
}

void MovingObject::setDirection(Direction direction)
{
	_direction = direction;

	float rotation;
	switch(direction){
		case UP:
			rotation = -90;
			break;
		case RIGHT:
			rotation = 0;
			break;
		case DOWN:
			rotation = 90;
			break;
		default:
			rotation = 180;
			break;
	}
	rotateTo(rotation);
}

void MovingObject::update(int dt)
{
	if(isMoving())
	{
		switch(_direction){
			case UP:
				moveByOffset(0, -_maxspeed*dt);
				break;
			case RIGHT:
				moveByOffset(_maxspeed*dt, 0);
				break;
			case DOWN:
				moveByOffset(0, _maxspeed*dt);
				break;
			case LEFT:
				moveByOffset(-_maxspeed*dt, 0);
				break;
		}
	}

	GObject::update(dt);
}

void MovingObject::moveTo(float x, float y)
{
	Play::getInstance()->removeFromField(this);
	Play::getInstance()->objectTryMove(this, &x, &y);
	GObject::moveTo(x, y);
	Play::getInstance()->registerAtField(this);
}

void MovingObject::moveByOffset(float dx, float dy)
{
	moveTo(getX()+dx, getY()+dy);
}